
//
//  HHPLivingViewCell.m
//  HHPLiveVideo
//
//  Created by 韩红坡 on 2017/4/25.
//  Copyright © 2017年 韩红坡. All rights reserved.
//

#import "HHPLivingViewCell.h"
#import "HHPLiveModel.h"

@interface HHPLivingViewCell ()

@property (nonatomic, strong) HHPLiveModel *liveModel;

/** 直播播放器 */
@property (nonatomic, strong) IJKFFMoviePlayerController *moviePlayer;

/** 直播开始前的占位图片 */
@property (nonatomic, strong) UIImageView *placeHolderView;

@end

@implementation HHPLivingViewCell
#pragma mark - life cycle
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = ViewBgColor;
        
        [self initViews];
    }
    return self;
}

#pragma mark - HHPTableViewCellProtocol
- (void)setCellModel:(HHPLiveModel *)cellModel
{
    NSLog(@"haha:%s, %d, %p, %p", __func__, __LINE__, self.liveModel, cellModel);
    NSLog(@"%s, %d, cell.y = %f", __func__, __LINE__, self.top);
    if (self.liveModel != cellModel) {
        NSLog(@"%s, %d 不相同", __func__, __LINE__);
        self.liveModel = cellModel;
        
        [self.placeHolderView sd_setImageWithURL:[NSURL URLWithString:self.liveModel.bigpic] placeholderImage:[UIImage imageNamed:@"profile_user"] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.placeHolderView.image = [image imageByBlurSoft];
        }];
//        [MBProgressHUD showLoadingMessage:@"努力加载中..."];
//        [self playLiveFlv];
    }
}

//- (void)didEndDisplay
//{
//    NSLog(@"haha:%s, %d, %p", __func__, __LINE__, self.liveModel);
//    
//    if (_moviePlayer) {
//        [_moviePlayer shutdown];
//        [_moviePlayer.view removeFromSuperview];
//        _moviePlayer = nil;
//        [[NSNotificationCenter defaultCenter] removeObserver:self];
//    }
//    
//    _placeHolderView.hidden = NO;
//}

#pragma mark - private methods
- (void)initViews
{
    [self.contentView addSubview:self.placeHolderView];
    
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews
{
    [self.placeHolderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.contentView);
    }];
}

- (void)playLiveFlv
{
    if (_moviePlayer) {
        [_moviePlayer shutdown];
        [_moviePlayer.view removeFromSuperview];
        _moviePlayer = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    [self.placeHolderView sd_setImageWithURL:[NSURL URLWithString:self.liveModel.bigpic] placeholderImage:[UIImage imageNamed:@"profile_user"] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.placeHolderView.image = [image imageByBlurSoft];
    }];
    
    IJKFFOptions *options = [IJKFFOptions optionsByDefault];
    
    IJKFFMoviePlayerController *moviePlayer = [[IJKFFMoviePlayerController alloc] initWithContentURLString:self.liveModel.flv withOptions:options];
    
    [self.contentView insertSubview:moviePlayer.view atIndex:0];
    
    [moviePlayer.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.contentView);
    }];
    
    [moviePlayer prepareToPlay];
    
    [self initObserver];
    
    self.moviePlayer = moviePlayer;
}

- (void)initObserver
{
    // 监听视频是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinish) name:IJKMPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadStateDidChange) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:self.moviePlayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStateDidChange) name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
}

#pragma mark - Notification method
- (void)playbackStateDidChange
{
    HHPLog(@"%s, %d, playbackState = %ld", __func__, __LINE__, self.moviePlayer.playbackState);
//    IJKMPMoviePlaybackStateStopped,
//    IJKMPMoviePlaybackStatePlaying,
//    IJKMPMoviePlaybackStatePaused,
//    IJKMPMoviePlaybackStateInterrupted,
//    IJKMPMoviePlaybackStateSeekingForward,
//    IJKMPMoviePlaybackStateSeekingBackward
    if (self.moviePlayer.playbackState == IJKMPMoviePlaybackStatePlaying) {
//        [_placeHolderView removeFromSuperview];
//        _placeHolderView = nil;
        _placeHolderView.hidden = YES;
        HHPLog(@"%s, %d", __func__, __LINE__);
    }
}

- (void)loadStateDidChange
{
//    IJKMPMovieLoadStateUnknown        = 0,
//    IJKMPMovieLoadStatePlayable       = 1 << 0,
//    IJKMPMovieLoadStatePlaythroughOK  = 1 << 1, // Playback will be automatically started in this state when shouldAutoplay is YES
//    IJKMPMovieLoadStateStalled        = 1 << 2,
    HHPLog(@"%s, %d loadState = %ld", __func__, __LINE__, self.moviePlayer.loadState);
    if ((self.moviePlayer.loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        if (!self.moviePlayer.isPlaying) {
            HHPLog(@"%s, %d isPlaying", __func__, __LINE__);
            [self.moviePlayer play];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [_placeHolderView removeFromSuperview];
//                _placeHolderView = nil;
                _placeHolderView.hidden = YES;
                HHPLog(@"%s, %d remove _placeHolderView", __func__, __LINE__);
//                [MBProgressHUD hideHUD];
            });
        }else{
            HHPLog(@"%s, %d 如果是网络状态不好, 断开后恢复, 也需要去掉加载", __func__, __LINE__);
            // 如果是网络状态不好, 断开后恢复, 也需要去掉加载
//            [MBProgressHUD hideHUD];
        }
    }else if (self.moviePlayer.loadState & IJKMPMovieLoadStateStalled){ // 网速不佳, 自动暂停状态
//        [MBProgressHUD showLoadingMessage:@"努力加载中..."];
        HHPLog(@"%s, %d 网速不佳, 自动暂停状态", __func__, __LINE__);
    }
}

- (void)didFinish
{
    NSLog(@"加载状态...%ld %ld %s", self.moviePlayer.loadState, self.moviePlayer.playbackState, __func__);
    // 因为网速或者其他原因导致直播stop了, 也要显示GIF
//    if (self.moviePlayer.loadState & IJKMPMovieLoadStateStalled && !self.parentVc.gifView) {
//        [self.parentVc showGifLoding:nil inView:self.moviePlayer.view];
//        return;
//    }
    //    方法：
    //      1、重新获取直播地址，服务端控制是否有地址返回。
    //      2、用户http请求该地址，若请求成功表示直播未结束，否则结束
//    __weak typeof(self)weakSelf = self;
//    [[MGNetworkTool shareNetworkTool] GET:self.live.flv parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"请求成功%@, 等待继续播放", responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"请求失败, 加载失败界面, 关闭播放器%@", error);
//        [weakSelf.moviePlayer shutdown];
//        [weakSelf.moviePlayer.view removeFromSuperview];
//        weakSelf.moviePlayer = nil;
//        weakSelf.endView.hidden = NO;
//    }];
}

#pragma mark - getter and setter
- (UIImageView *)placeHolderView {
    if (!_placeHolderView) {
        _placeHolderView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile_user"]];
    }
    return _placeHolderView;
}






@end






